package com.ato.IO;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author wangjing
 * @create 2021--12--09--20:46
 * 处理字节流
 */
public class IOFileInputStreamTest {
    @Test
    public void test1() {
//        1:提供File  指明要写入哪里
        FileInputStream fileInputStream = null;

        try {
            File file = new File("hello.txt");
//        2:提供FileInputStream
            fileInputStream = new FileInputStream(file);
//        3: 读数据
            byte[] buffer = new byte[5];
            int len;
            while ((len = fileInputStream.read(buffer)) != -1) {
                String s = new String(buffer, 0, len);
//                 注意 读取字节流时，文本中文可能会出现乱码。
                System.out.print(s);
            }
//        4：关闭流
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void copyPicTest() {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        try {
            File file = new File("C:\\Users\\wangjing\\Desktop\\123.mp4");
            File file2 = new File("testFileInputStream.mp4");
            fi = new FileInputStream(file);
            fo = new FileOutputStream(file2);
//            这个可以设置为1024  因为一般复制的话可能是视频这种大的文件
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fi.read(buffer)) != -1) {
                fo.write(buffer, 0, len);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fo != null) fi.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fi != null) fi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}